<template>
  <div id="app-container">
    <!-- 所有登录用户都进入 DashboardPage，根据 role 显示不同导航栏 -->
    <DashboardPage
      v-if="isLoggedIn"
      :account="userAccount"
      :current-password="userPassword"
      :user-role="userRole"
      :user-name="userName"
      @logout="handleLogout"
      @password-change="handlePasswordChange"
    />
    <HomePage v-else @show-login="handleShowLogin" />

    <LoginPage
      v-if="showLoginModal"
      @close="handleCloseLogin"
      @login-success="handleLoginSuccess"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import HomePage from './components/HomePage.vue';
import DashboardPage from './components/DashboardPage.vue';
import LoginPage from './components/LoginPage.vue';
import axios from 'axios';


const isLoggedIn = ref(false);
const showLoginModal = ref(false);
const userAccount = ref('');
const userPassword = ref('');
const userRole = ref('');
const userName = ref('');

// 验证 token 并获取用户信息
const validateTokenAndGetUserInfo = async (token) => {
  try {
    const response = await axios.get('http://47.93.134.56:8800/user/validate', {
      headers: {
        'token': token
      }
    });
    
    if (response.data.code === 200) {
      // token 有效，获取用户信息
      const userData = response.data.data;
      userAccount.value = userData.account || '';
      userRole.value = userData.role || '';
      userName.value = userData.name || '';
      return true;
    } else {
      // token 无效
      localStorage.removeItem('token');
      return false;
    }
  } catch (error) {
    console.error('验证 token 失败:', error);
    localStorage.removeItem('token');
    return false;
  }
};

// 从 localStorage 恢复登录状态
const restoreLoginState = async () => {
  const token = localStorage.getItem('token');
  
  if (token && token.trim() !== '') {
    // token 存在且不为空，验证 token 并获取用户信息
    const axios = require('axios');
    axios.defaults.headers.common['token'] = token;
    
    const isValid = await validateTokenAndGetUserInfo(token);
    if (isValid) {
      isLoggedIn.value = true;
      console.log('Token 有效，保持登录状态');
    } else {
      isLoggedIn.value = false;
      console.log('Token 无效，需要重新登录');
    }
  } else {
    // token 不存在或为空，需要重新登录
    isLoggedIn.value = false;
    console.log('Token 不存在，需要重新登录');
  }
};

const handleShowLogin = () => {
  showLoginModal.value = true;
};

const handleCloseLogin = () => {
  showLoginModal.value = false;
};

const handleLoginSuccess = (account, password, role, name) => {
  userAccount.value = account;
  userPassword.value = password;
  userRole.value = role;
  userName.value = name;
  isLoggedIn.value = true;
  showLoginModal.value = false;
};

const handleLogout = () => {
  isLoggedIn.value = false;
  userAccount.value = '';
  userPassword.value = '';
  userRole.value = '';
  userName.value = '';
  // 清除 localStorage 中的登录信息
  localStorage.removeItem('token');
  // 清除 axios 默认 header
  const axios = require('axios');
  delete axios.defaults.headers.common['token'];
};

const handlePasswordChange = (newPassword) => {
  userPassword.value = newPassword;
};

// 页面加载时恢复登录状态
onMounted(() => {
  restoreLoginState().catch(error => {
    console.error('恢复登录状态时发生错误:', error);
    isLoggedIn.value = false;
  });
});
</script>

<style>
/* Global styles */
html,
body,
#app {
  height: 100%;
  margin: 0;
  padding: 0;
}

#app-container {
  height: 100%;
  width: 100%;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
  /* background-color: #f4f7f9; */
}
</style>
